package com.xuecheng.base.interceptor;

import com.xuecheng.base.exception.XueChengPlusException;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Copyright 2023 ZS Network Co., Ltd. All rights reserved.
 * 本文件仅限于正数网络技术有限公司内部传阅，禁止外泄以及用于其他的商业目的。
 * Created by hes on 2023/11/610:30
 */
@Slf4j
@Configuration
public class FeginRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest request;
        try {
            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            log.warn("获取HTTP上下文失败 >>> {}", e.getMessage());
            throw new XueChengPlusException("获取HTTP上下文失败");
        }

        if (request != null) {
            Map<String, String> headers = getHeaders(request);
            String token = headers.get("token");
            if (StringUtils.isBlank(token)) {
                log.warn("token为空");
            }
        }
    }

    private Map<String, String> getHeaders(HttpServletRequest httpServletRequest) {
        HashMap<String, String> headers = new HashMap<>();
        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String headerValue = httpServletRequest.getHeader(key);
            headers.put(key, headerValue);
        }
        return headers;
    }
}
